<!--
 * @Author: cjx
 * @Date: 2022-12-26 14:22:02
 * @LastEditTime: 2023-04-19 17:33:45
 * @Description: 多选框组
-->
<template>
  <CheckboxGroup v-model="computedValue" v-bind="$attrs" @on-change="onChange">
    <Checkbox v-for="item in dataList" :label="item.value" :disabled="$attrs.disabled || item.disabled">
      {{ item.label }}
    </Checkbox>
  </CheckboxGroup>
</template>

<script setup lang="ts">
import { apiFindDictList } from '@/api/common'
import { computed } from '@vue/reactivity'
import { onBeforeMount, ref, type Ref } from 'vue'
const props = defineProps({
  modelValue: {
    type: [String, Array],
    default: ''
  },
  list: {
    // 自定义选项
    type: Array,
    default: () => []
  },
  type: {
    // 字典类型
    type: String,
    default: ''
  },
  pVal: {
    // 父级值
    type: String,
    default: ''
  },
  pId: {
    // 父级id
    type: String,
    default: '-1'
  }
})

const emits = defineEmits(['update:modelValue', 'on-change'])
const computedValue = computed({
  get: () => {
    const typeOfVal = Object.prototype.toString.call(props.modelValue)
    if (typeOfVal.includes('Array')) {
      return props.modelValue
    } else if (typeOfVal.includes('String')) {
      // 防止ts报错，加上类型判断
      return typeof props.modelValue === 'string' && props.modelValue.split(',').filter((item) => item !== '')
    }
  },
  set: (val) => {
    emits('update:modelValue', val)
  }
})

// 获取选项
interface IcheckboxItem {
  label: string
  value: string
  disabled?: boolean
}
let dataList: Ref<IcheckboxItem[]> = ref([])
const getList = () => {
  if (!props.list.length) {
    if (props.type) {
      // 不存在自定义数据，且字典类型存在时，接口获取字典
      apiFindDictList({
        type: props.type,
        parentId: props.pId,
        parentValue: props.pVal
      }).then((res) => {
        const { isSuccess, errorMsg, errmsg, data } = res || {}
        if (isSuccess) {
          dataList.value = data
        } else {
          window.$Message.error(errorMsg || errmsg)
        }
      })
    }
  } else {
    dataList.value = props.list as IcheckboxItem[]
  }
}

onBeforeMount(() => {
  getList()
})

// 选择回调
const onChange = (val: string[]) => {
  const valStr = val.join()
  emits('update:modelValue', valStr)
  const valArr = dataList.value.filter((item) => val.includes(item.value))

  // 返回字符串拼接值，以及已选项
  emits('on-change', valStr, valArr)
}
</script>
